import os, sys


import mimetypes
mimetypes.add_type("application/blender", ".blend")

class AnalyzerException(Exception):
  def __init__(self, msg):
    self.msg = msg
  def __str__(self):
    return repr(self.msg)
    
class AnalyzerFileException(AnalyzerException):
  pass
  
class AnalyzerUnknownTypeException(AnalyzerException):
  pass

class BaseAnalyzer(object):
  pass
  
from yapsy.PluginManager import PluginManager
class Analyzer(PluginManager):
  """
  Analyze files and tries to find known assets types in it.
  """
  analyzers = {}
  
  def __init__(self):
    Analyzer.analyzers = {}
    PluginManager.__init__(self, categories_filter={"Analyzer": BaseAnalyzer}, plugin_info_ext="analyzer")
    path = os.path.join(os.path.abspath(os.path.dirname(__file__)),"analyzers")
    self.setPluginPlaces([path])
    
    
    self.locatePlugins()
    self.loadPlugins()
    
    for plugin in self.getAllPlugins():
      for format in plugin.plugin_object.handled_types:
        self.analyzers[format] = plugin.plugin_object


  def AnalyzePath(self, anURI):
    assets = []
    for top, dirs, files in os.walk(anURI):
      #Excludes
      if ".svn" in dirs:
        dirs.remove (".svn")
      for f in files:
        try:
          assets.append( self.AnalyzeFile(os.path.join(top, f)) )
        except AnalyzerException as e:
          print(e.msg)
      for d in dirs:
        assets.extend( self.AnalyzePath(os.path.join(top, d)) )
    return assets

              
  def AnalyzeFile(self, anURI):
    if not os.path.exists(anURI) and not os.path.isdir(anURI):
      raise AnalyzerFileException('E: Analyzer: No such file "%s"!'%(anURI))
    format = mimetypes.guess_type(anURI, False)[0]
    if format in self.analyzers:
      fileRef = self.analyzers[format].analyze(anURI)
      return fileRef
    else:
      raise AnalyzerUnknownTypeException("E: Analyzer: No analyzer for %s (file: %s)"%(format, anURI))
      
  def RemoveURI(self, anURI):
    pass
    file = _GetFile(fullFileName=anURI)
    if file:
      children = File.objects.filter(parent=file)
      for child in children:
        RemoveURI(child.fullFileName)
      for asset in file.asset_set.all():
        self._DeleteAssetCache(asset)  
      file.delete()
       
